#!/usr/bin/ruby
# Copyright 2011, Dell
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 

require 'rubygems'
require 'json'
require 'net/http'
require 'net/http/digest_auth'

# we only accept json, because we want to parse it.
@headers = {"Accept" => "application/json", 
  "Content-Type" => "application/json" }

@username = "crowbar"
@password = "crowbar"

def die(ret, msg)
  STDERR.puts(msg) if ENV["DEBUG"] == "true"
  exit(ret)
end

def authenticate(req,uri,data=nil)
  uri.user=@username
  uri.password=@password
  res=nil
  begin
    Net::HTTP.start(uri.host, uri.port) {|http|
      r = req.new(uri.request_uri,@headers)
      r.body = data if data
      res = http.request r
      if res['www-authenticate']
        digest_auth=Net::HTTP::DigestAuth.new
        auth=Net::HTTP::DigestAuth.new.auth_header(uri,
                                                   res['www-authenticate'],
                                                   req::METHOD)
        r.add_field 'Authorization', auth
        res = http.request r
      end
    }
    res
  rescue
    die(2,"Could not talk to Crowbar")
  end
end

node = ARGV[0]
admin_node=ENV["CROWBAR_IP"]
target_state=ENV["TARGET_STATE"]
admin_node = '192.168.124.10' if not admin_node
target_state = 'ready' unless target_state
conn = ''
res = authenticate(Net::HTTP::Get,
                   URI.parse("http://#{admin_node}:3000/crowbar/machines/1.0/show?name=#{node}"))
die(4,"Did not get good response from Crowbar") unless res.code == '200'
state = JSON.parse(res.body)
puts "#{node} is #{state["state"]}."
exit 0 if state["state"] == target_state
exit 1
